package com.xiyue.leaspring.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ParameterizedPreparedStatementSetter;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.xiyue.leaspring.dao.INewsDao;
import com.xiyue.leaspring.vo.News;

@Repository
public class NewsDaoImpl implements INewsDao {

	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public News findById(Long nid) {
		String sql = "select nid,title,pubdate,note,price,readcount from news where nid=?";
		return this.jdbcTemplate.queryForObject(sql, new Object[] {nid},new RowMapper<News>() {

			@Override
			public News mapRow(ResultSet rs, int rowNum) throws SQLException {
				News vo = new News();
				vo.setNid(rs.getLong(1));
				vo.setTitle(rs.getString(2));
				vo.setPubDate(rs.getDate(3));
				vo.setNote(rs.getString(4));
				vo.setPrice(rs.getDouble(5));
				vo.setReadCount(rs.getInt(6));
				return vo;
			}
			
		});
	}

	@Override
	public boolean doUpdate(News vo) {
		String sql = "UPDATE news SET title=?,pubdate=?,note=?,price=?,readcount=? "
				+ "WHERE nid=?";
		int len = this.jdbcTemplate.update(sql,vo.getTitle(),vo.getPubDate(),vo.getNote(),
				vo.getPrice(),vo.getReadCount(),vo.getNid());
		return len>0;
	}

	@Override
	public boolean doRemove(Long nid) {
		return this.jdbcTemplate.update("DELETE FROM news WHERE nid=?",nid)>0;
	}

	@Override
	public int doSave(News vo) {
		String sql = "INSERT INTO news(title,pubdate,note,price,readcount)VALUES(?,?,?,?,?)";
		return this.jdbcTemplate.update(new PreparedStatementCreator() {
			
			@Override
			public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
				PreparedStatement ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
				ps.setString(1,vo.getTitle());
				ps.setDate(2,new java.sql.Date(vo.getPubDate().getTime()));
				ps.setString(3,vo.getNote());
				ps.setDouble(4,vo.getPrice());
				ps.setInt(5,vo.getReadCount());
				return ps;
			}
		});
	}

	@Override
	public void batchSave(List<News> allnews) {
		String sql = "INSERT INTO news(title,pubdate,note,price,readcount)VALUES(?,?,?,?,?)";
		this.jdbcTemplate.batchUpdate(sql, allnews,allnews.size(),new ParameterizedPreparedStatementSetter<News>() {

			@Override
			public void setValues(PreparedStatement ps, News vo) throws SQLException {
				ps.setString(1,vo.getTitle());
				ps.setDate(2,new java.sql.Date(vo.getPubDate().getTime()));
				ps.setString(3,vo.getNote());
				ps.setDouble(4,vo.getPrice());
				ps.setInt(5,vo.getReadCount());
			}
		});
		
	}

}
